import {Injectable} from '@angular/core';
import {Menu} from '../entity/menu.model';
import {AppConfig} from '../config';
import {MenuFavorite} from '../entity/menu_favorite.model';
import {MenuShortcut} from '../entity/menu_shortcut.model';
import {Observable} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {InterceptorService} from './interceptor/interceptor-service';

/**
 * 菜单服务
 *
 * @export
 * @class MenuService
 */
@Injectable()
export class MenuService {
  [x: string]: any;

  private readonly param = 'menus';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {
  }

  /**
   * 获得所有菜单
   *
   * @returns {Promise<Menu[]>}
   * @memberof MenuService
   */
  public getMenus(): Promise<Menu[]> {
    return this.http.get(this.url, {headers: this.headers})
      .toPromise()
      .then(response => response.data as Menu[])
      .catch(this.handleError);
  }

  /**
   * 创建菜单
   *
   * @param {Menu} menu
   * @returns {Promise<Menu>}
   * @memberof MenuService
   */
  public create(menu: Menu): Promise<Menu> {
    return this.http.post(this.url, JSON.stringify(menu)).toPromise().then(result => {
      try {
        switch (result.code) {
          case '200':
            return result.data as Menu;
          case '-1':
            throw new Error(result.message);
        }
      }
      catch (error) {
        this.handleError(error);
      }
    })
      .catch(this.handleError);
  }

  /**
   * 更新多级菜单
   *
   * @param {Menu[]} menus
   * @returns {Promise<Menu[]>}
   * @memberof MenuService
   */
  public batchUpdate(menus: Menu[]): Promise<Menu[]> {
    const url = `${this.url}`;
    return this.http.put(url, JSON.stringify(menus))
      .toPromise()
      .then(() => menus)
      .catch(this.handleError);
  }

  /**
   * 更新菜单
   *
   * @param {Menu} menu
   * @returns {Promise<Menu>}
   * @memberof MenuService
   */
  public update(menu: Menu): Promise<Menu> {
    const url = `${this.url}`;
    return this.http.put(url, JSON.stringify(menu))
      .toPromise()
      .then(() => menu)
      .catch(this.handleError);
  }

  /**
   * 批量删除
   *
   * @param {number[]} menuIds
   * @returns {Promise<boolean>}
   * @memberof MenuService
   */
  public batchDelete(menuIds: number[]): Promise<any> {
    const apiUrl = `${this.url}?items=${menuIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        console.log(response)
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return result;
            case '8001':
              return result;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }


  /**
   * 根据菜单名称查询菜单集合
   *
   * @param {string} menuName
   * @returns {Promise<Menu[]>}
   * @memberof MenuService
   */
  public getMenusByMenuName(menuName: string): Promise<Menu[]> {
    return this.http.get(`${this.url}/menuName/${menuName}`)
      .toPromise()
      .then(response => {
        return response.data as Menu[]
      })
      .catch(this.handleError);
  }


  /**
   * 在同一级别菜单下是否存在相同的菜单名称
   *
   * @param {string} menuName
   * @param {number} menuId
   * @returns {Observable<boolean>}
   * @memberof MenuService
   */
  public hasMenuByMenuName(menuName: string, parentId: number, menuId: number): Observable<boolean> {
    const url = `${this.url}/menuName/${menuName}/parentId/${parentId}/menuId/${menuId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }

  /**
   * 根据用户id用户菜单信息
   *
   * @param {number} userId
   * @returns {Promise<{ access: MenuAccess[]; favorite: MenuFavorite[]; shortcut: MenuShortcut[] }>}
   * @memberof MenuService
   */
  public getMenuProfilesByUserId(userId: number): Promise<{ access: Menu[]; favorite: MenuFavorite[]; shortcut: MenuShortcut[] }> {
    return this.http.get(`${this.url}/profiles/userId/${userId}`)
      .toPromise()
      .then(response => {
        return response.data;
      })
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }
}


// WEBPACK FOOTER //
// ./src/app/service/menu.service.ts
